<template>
  <div class="pt-54px md:pt-54px">
    <!-- 视频轮播区域 -->
    <section class="relative">
      <div class="banner">
        <!-- 装饰性边框 -->
        <div class="banner__left"></div>
        <div class="banner__right"></div>
        <div class="banner__top"></div>
        <div class="banner__bottom"></div>

        <!-- 播放按钮 -->
        <NuxtLink v-if="btnLink" :to="btnLink" class="swiper-slide__play-btn">
          <el-icon><component :is="CaretRight" /></el-icon>
          播放
        </NuxtLink>

        <!-- Swiper 视频轮播 -->
        <swiper
            :modules="modules"
            :slides-per-view="1"
            :loop="true"
            :autoplay="{
            delay: 15000,
            pauseOnMouseEnter: true,
            disableOnInteraction: false,
          }"
            :pagination="{
            clickable: true,
          }"
            class="h-40vh md:h-70vh"
            @slide-change="onSlideChange"
        >
          <swiper-slide v-for="(item, index) in banners" :key="item.bannerId">
            <video
                :ref="el => { if (el) videoRefs[index] = el as HTMLVideoElement }"
                muted
                :autoplay="index === 0"
                preload="metadata"
                :poster="item.img"
                :src="item.videoUrl || item.url"
                class="banner-video h-40vh w-full object-cover md:h-70vh"
            />
          </swiper-slide>
        </swiper>
      </div>
    </section>

    <!-- 动态栏目区域 -->
    <div class="container mx-auto px-4 md:px-6 lg:px-8">
      <section v-for="column in columns" :key="column.columnId" class="mb-8 md:mb-10">
        <div class="flex justify-between items-center mb-4">
          <NuxtLink :to="`/column/${column.columnValue}`" class="text-lg md:text-xl text-white hover:text-green-400 font-semibold">
            {{ column.columnName }}
          </NuxtLink>

          <!-- 子栏目标签 -->
          <div v-if="column.subColumns && column.subColumns.length > 0" class="genre flex gap-x-3 md:gap-x-5">
            <NuxtLink
                v-for="subCol in column.subColumns"
                :key="subCol.columnId"
                :to="`/column/${column.columnValue}/show?columnId=${subCol.columnId}`"
                class="text-gray-400 hover:text-green-400 text-xs md:text-sm"
            >
              {{ subCol.name }}
            </NuxtLink>
          </div>
        </div>

        <!-- 影视列表 -->
        <div class="video-list">
          <ul>
            <li v-for="movie in column.movies" :key="movie.movieBasicsId">
              <MovieCard2 :movie="movie" />
            </li>
          </ul>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Autoplay, Pagination } from 'swiper/modules'
import { CaretRight } from '@element-plus/icons-vue'
import 'swiper/css'
import 'swiper/css/pagination'

// Swiper模块
const modules = [Autoplay, Pagination]

// 视频播放控制
const currIndex = ref(0)
const videoRefs = ref<HTMLVideoElement[]>([])
const btnLink = ref('')
const siteConfig = useSiteConfig()

// SEO设置
useSeoMeta({
  title: '首页',
  description: siteConfig.siteDescription,
  ogTitle: siteConfig.siteName,
  ogDescription: siteConfig.siteDescription,
})

// 树形数据转换函数
const handleTree = (data: any[], id?: string, parentId?: string, children?: string) => {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  const childrenListMap: any = {}
  const treeData: any[] = []

  for (const d of data) {
    const itemId = d[config.id]
    childrenListMap[itemId] = d
    if (!d[config.childrenList]) {
      d[config.childrenList] = []
    }
  }

  for (const d of data) {
    const parentNodeId = d[config.parentId]
    const parentObj = childrenListMap[parentNodeId]
    if (!parentObj) {
      treeData.push(d)
    } else {
      if (!parentObj[config.childrenList]) {
        parentObj[config.childrenList] = []
      }
      parentObj[config.childrenList].push(d)
    }
  }
  return treeData
}

// 判断是否为叶子节点（无子节点）
const isLeafNode = (node: any) => {
  return !node.children || node.children.length === 0
}
// 获取轮播图数据
const { data: banners } = await useFetch('/dev-api/app/cms/banners', {
  transform: (res: any) => {
    // 后端返回的是数组，不是{rows: []}格式
    const rows = Array.isArray(res) ? res : (res.data || [])
    if (rows.length > 0) {
      btnLink.value = rows[0].url || ''
    }
    return rows
  }
})

// 获取所有栏目并树形化
const { data: allColumns } = await useFetch('/dev-api/app/basic/columns', {
  transform: (res: any) => {
    // 后端返回的数据格式：可能是数组或 {data: []}
    const rawData = Array.isArray(res) ? res : (res.data || [])
    // 转换为树形结构，使用 columnId 作为主键，parentId 作为父级ID
    return handleTree(rawData, 'columnId', 'parentId', 'children')
  }
})

// 递归函数：为叶子节点获取电影数据
const fetchMoviesForLeafNodes = async (nodes: any[], parentNode?: any): Promise<any[]> => {
  const results: any[] = []

  for (const node of nodes) {
    // 如果是叶子节点（没有子节点），则查询电影
    if (isLeafNode(node)) {

      // 获取该栏目的影视列表
      const moviesRes = await $fetch('/dev-api/app/movieapp/list', {
        query: {
          searchValue: 'ALL',
          columnValue: node.columnId,
          pageSize: 12,
          status: '0'
        }
      })

      // 获取子栏目：如果有父节点，则显示父节点的所有子节点（兄弟节点）
      const subColumns = parentNode && parentNode.children
          ? parentNode.children.slice(0, 6)
          : []

      results.push({
        columnId: node.columnId,
        columnName: node.name,
        columnValue: node.value,
        movies: (moviesRes as any).rows || [],
        subColumns: subColumns // 显示兄弟节点作为子栏目标签
      })
    } else {
      // 如果有子节点，递归处理子节点
      const childResults = await fetchMoviesForLeafNodes(node.children || [], node)
      results.push(...childResults)
    }
  }

  return results
}

// 为每个叶子节点获取影视数据
const columns = ref<any[]>([])
if (allColumns.value && allColumns.value.length > 0) {
  columns.value = await fetchMoviesForLeafNodes(allColumns.value)
}

// Swiper 切换事件
const onSlideChange = (swiper: any) => {
  currIndex.value = swiper.activeIndex

  // 更新播放按钮链接
  if (banners.value && banners.value[currIndex.value]) {
    btnLink.value = banners.value[currIndex.value].url || ''
  }

  // 控制视频播放
  videoRefs.value.forEach((video: HTMLVideoElement, index: number) => {
    if (video) {
      if (index === currIndex.value) {
        video.play().catch(() => {
          // 自动播放可能被浏览器阻止，静默处理
        })
      } else {
        video.pause()
      }
    }
  })
}
</script>

<style scoped lang="scss">
// Banner 样式
.banner {
  position: relative;
  overflow: hidden;

  // 装饰性边框
  &__left {
    background: linear-gradient(-90deg, rgba(255, 255, 255, 0) 0%, #111214 100%);
    width: 250px;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    pointer-events: none;
  }

  &__right {
    background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, #111214 100%);
    width: 250px;
    height: 100%;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 2;
    pointer-events: none;
  }

  &__top {
    background: linear-gradient(180deg, #111214 0%, rgba(255, 255, 255, 0) 100%);
    width: 100%;
    height: 100px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    pointer-events: none;
  }

  &__bottom {
    background: linear-gradient(0deg, #111214 0%, rgba(255, 255, 255, 0) 100%);
    width: 100%;
    height: 100px;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 2;
    pointer-events: none;
  }
}

// 播放按钮
.swiper-slide__play-btn {
  position: absolute;
  right: 50px;
  bottom: 50px;
  z-index: 10;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 25px;
  color: #111214;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #fff;
    transform: scale(1.05);
  }

  @media (max-width: 768px) {
    right: 20px;
    bottom: 20px;
    padding: 8px 16px;
    font-size: 14px;
  }
}

// 视频列表样式
.video-list {
  ul {
    display: grid;
    gap: 8px;

    // 移动端：每行3个，卡片宽度约110px
    grid-template-columns: repeat(3, minmax(0, 1fr));

    // 平板：每行4-5个
    @media (min-width: 640px) {
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 12px;
    }

    // 小屏电脑：每行6个
    @media (min-width: 768px) {
      grid-template-columns: repeat(6, minmax(0, 1fr));
      gap: 14px;
    }

    // 中屏电脑：每行8个
    @media (min-width: 1024px) {
      grid-template-columns: repeat(8, minmax(0, 1fr));
      gap: 16px;
    }

    // 大屏电脑：每行10个
    @media (min-width: 1280px) {
      grid-template-columns: repeat(10, minmax(0, 1fr));
      gap: 18px;
    }

    // 超大屏：每行12个
    @media (min-width: 1536px) {
      grid-template-columns: repeat(12, minmax(0, 1fr));
      gap: 20px;
    }

    li {
      list-style: none;
      width: 100%;
      max-width: 200px; // 限制最大宽度
      margin: 0 auto; // 居中
    }
  }
}

// Swiper 分页样式
:deep(.swiper-pagination-bullet) {
  background: rgba(255, 255, 255, 0.5);
  width: 8px;
  height: 8px;
}

:deep(.swiper-pagination-bullet-active) {
  background: #fff;
  width: 24px;
  border-radius: 4px;
}

:deep(.swiper-pagination) {
  bottom: 20px;
  z-index: 10;
}
</style>
